{% extends 'base/base.html' %}
{% load humanize %}
{% load permission_tags %}
{% load static %}

{% block title %}
Profile
{% endblock title %}

{% block custom_js_css_link %}
{% endblock custom_js_css_link %}

{% block page_title %}
Admin Settings
{% endblock page_title %}

{% block breadcrumb_title %}
<li class="breadcrumb-item"><a href="/{{current_project.slug}}/">Dashboard</a></li>
<li class="breadcrumb-item active">Admin Settings</li>
{% endblock breadcrumb_title %}

{% block main_content %}
<div class="row">
   <div class="col-12">
      <div class="card">
         <div class="card-body">
            <div class="row justify-content-between">
               <div class="col-md-12">
                  <div class="text-md-end mt-3 mt-md-0">
                     <button type="button" class="btn btn-primary waves-effect waves-light" onclick="create_user_modal()"><i class="mdi mdi-plus-circle me-1"></i> Add User</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>
<div class="row">
  <div class="col-12">
    <div class="card">
      <div class="card-body">
        <h4>Users</h4>
        <div class="table-responsive pt-3">
          <table class="table table-centered table-nowrap table-borderless mb-0">
            <thead class="table-light">
              <tr>
                <th>Username</th>
                <th>Name</th>
                <th>Role</th>
                <th>Created on</th>
                <th>Last Logged in</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {% for muser in users %}
              <tr>
                <th>
                  {% if muser|has_role:'admin' %}
                    <span class="badge bg-soft-success text-success p-1">{{muser.username}}</span>
                  {% elif muser|has_role:'auditor' %}
                    <span class="badge bg-soft-pink text-pink p-1">{{muser.username}}</span>
                  {% else %}
                    <span class="badge bg-soft-primary text-primary p-1">{{muser.username}}</span>
                  {% endif %}
                </th>
                <th>
                  {% if muser.get_full_name %}
                  {{muser.get_full_name|escape}}
                  {% else %}
                  {{muser.username|escape}}
                  {% endif %}
                </th>
                <th>
                  {% if muser|has_role:'sys_admin' %}
                    <span class="badge bg-soft-success text-success p-1">Sys Admin</span>
                  {% elif muser|has_role:'auditor' %}
                    <span class="badge bg-soft-pink text-pink p-1">Auditor</span>
                  {% else %}
                  <span class="badge bg-soft-primary text-primary p-1">Penetration Tester</span>
                  {% endif %}
                </th>
                <td>{{muser.date_joined|naturaltime}}</td>
                <td>
                  {% if muser.last_login %}
                    {{muser.last_login|naturaltime}}
                  {% else %}
                    <span class="badge bg-soft-danger text-danger p-1">Never Logged In</span>
                  {% endif %}
                </td>
                <td>
                  {% if muser.is_active %}
                  <span class="badge bg-soft-success text-success p-1">Active</span>
                  {% else %}
                  <span class="badge bg-soft-danger text-danger p-1">Disabled</span>
                  {% endif %}
                </td>
                <td>
                  {% if user != muser %}
                    {% if muser.is_active %}
                    <a href="./update?mode=change_status&user={{ muser.id }}" class="action-icon" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Disable Account"> <i class="mdi mdi-account-cancel"></i></a>
                    {% else %}
                    <a href="./update?mode=change_status&user={{ muser.id }}" class="action-icon" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Enable Account"> <i class="mdi mdi-account-check"></i></a>
                    {% endif %}
                  {% else %}
                  &nbsp;
                  {% endif %}
                  <a href="#" onclick="update_user_modal({{muser.id}}, '{% if muser|has_role:'sys_admin' %}admin{% elif muser|has_role:'auditor'%}auditor{% elif muser|has_role:'penetration_tester'%}penetration_tester{%endif%}')" class="action-icon" id="change_user_details_btn" title="Update User Detail" data-bs-toggle="tooltip" data-bs-placement="bottom"> <i class="mdi mdi-account-edit"></i></a>
                  {% if user != muser %}
                    <a href="#" onclick="delete_user({{muser.id}}, '{{muser.username}}')" class="action-icon" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Delete Account"> <i class="mdi mdi-trash-can"></i></a>
                  {% endif %}
                </td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div> <!-- .table-responsive -->
      </div>
    </div>
  </div>
</div>
{% endblock main_content %}


{% block page_level_script %}
<script type="text/javascript">
function delete_user(id, username) {
  const delAPI = "./update?mode=delete&user=" + id;
  swal.queue([{
    title: 'Are you sure you want to delete user '+ htmlEncode(username) +'?',
    text: "You won't be able to revert this!",
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: 'Delete',
    padding: '2em',
    showLoaderOnConfirm: true,
    preConfirm: function() {
      return fetch(delAPI, {
        method: 'POST',
        credentials: "same-origin",
        headers: {
          "X-CSRFToken": getCookie("csrftoken")
        }
      })
      .then(function (response) {
        return response.json();
      })
      .then(function(data) {
        return location.reload();
      })
      .catch(function() {
        swal.insertQueueStep({
          type: 'error',
          title: 'Oops! Unable to delete the User!'
        })
      })
    }
  }])
}

function update_user_modal(user_id, permission){
  var html_content = '';

  html_content += `
  <div class="form mb-3">
    <label for="user_role" class="form-label float-start">Role</label>
    <select class="form-select" id="user_role">
    <option ${permission == 'sys_admin' ? 'selected': ''} value='sys_admin'>Sys Admin</option>
    <option ${permission == 'penetration_tester' ? 'selected': ''} value='penetration_tester'>Penetration Tester</option>
    <option ${permission == 'auditor' ? 'selected': ''} value='auditor'>Auditor</option>
    </select>
  </div>
  <div class="form mb-3">
    <label for="password" class="form-label float-start">Change Password</label>
    <div class="input-group input-group-merge">
      <input type="password" id="password" class="form-control" placeholder="Password">
    </div>
    <div class="form-check form-switch float-end mt-2">
      <input type="checkbox" class="form-check-input" id="show-password">
      <label class="form-check-label text-small" for="show-password" style="font-size: 12px;">Show Password</label>
    </div>
  </div>

  `;

  Swal.fire({
      title: 'Update User',
      html: html_content,
      showCloseButton: true,
      showCancelButton: false,
      confirmButtonText: 'Update',
      showLoaderOnConfirm: true,
      preConfirm: function () {
        return new Promise(function (resolve) {
          var role_selected = document.getElementById('user_role').value;
          var change_password = document.getElementById('password').value;
          const data = {
            'role': role_selected,
            'change_password': change_password
          };
          fetch('./update?mode=update&user=' + user_id, {
            method: 'POST',
            credentials: "same-origin",
            headers: {
              "X-CSRFToken": getCookie("csrftoken")
            },
            body: JSON.stringify(data)
          })
          .then(function (response) {
            return response.json();
          })
          .then(function(data) {
            return location.reload();
          })
          .catch(function() {
            swal.insertQueueStep({
              type: 'error',
              title: 'Oops! Unable to update user!'
            })
          })
          resolve()
        })
      }
  });

  const passwordInput = document.getElementById('password');
  const showPasswordCheckbox = document.getElementById('show-password');


  showPasswordCheckbox.addEventListener('change', function() {
    if (showPasswordCheckbox.checked) {
      passwordInput.type = 'text';
    } else {
      passwordInput.type = 'password';
    }
  });

}

function create_user_modal(){
  var html_content = '';

  html_content += `
  <div class="form mb-3">
    <label for="create_username" class="form-label float-start">Username</label>
    <input id="create_username" class="form-control" placeholder="Username" autocomplete="off">
  </div>
  <i class="fa fa-info-circle text-muted float-end" data-bs-container="#tooltip-container" data-bs-toggle="tooltip" data-bs-placement="bottom" title="- Sys Admin: Sys Admin is a super user that has permission to modify system and scan related configurations, scan engines, create new users, add new tools etc. Super user can initiate scans and subscans effortlessly.
- Penetration Tester: Penetration Tester will be allowed to modify and initiate scans and subscans, add or update targets, etc. A penetration tester will not be allowed to modify system configurations.
- Auditor: Auditor can only view and download the report. An auditor can not change any system or scan related configurations nor can initiate any scans or subscans."></i>
  <div class="form mb-3">
    <label for="create_user_role" class="form-label float-start">Role</label>
    <select class="form-select" id="create_user_role">
    <option value='sys_admin'>Sys Admin</option>
    <option value='penetration_tester'>Penetration Tester</option>
    <option value='auditor'>Auditor</option>
    </select>
  </div>
  <div class="form mb-3">
    <label for="create_password" class="form-label float-start">Create Password</label>
    <div class="input-group input-group-merge">
      <input type="password" id="create_password" class="form-control" placeholder="Password">
    </div>
    <div class="form-check form-switch float-end mt-2">
      <input type="checkbox" class="form-check-input" id="show-password">
      <label class="form-check-label text-small" for="show-password" style="font-size: 12px;">Show Password</label>
    </div>
  </div>

  `;

  Swal.fire({
      title: 'Create User',
      html: html_content,
      showCloseButton: true,
      showCancelButton: false,
      confirmButtonText: 'Create User',
      showLoaderOnConfirm: true,
      preConfirm: function () {
        return new Promise(function (resolve) {
          var create_username = document.getElementById('create_username').value;
          var role_selected = document.getElementById('create_user_role').value;
          var create_password = document.getElementById('create_password').value;
          if (!create_password) {
            Swal.fire({
              title: "Oops! Passwords can't be empty!",
              icon: 'error',
            })
            return
          }
          const data = {
            'username': create_username,
            'role': role_selected,
            'password': create_password
          };
          fetch('./update?mode=create', {
            method: 'POST',
            credentials: "same-origin",
            headers: {
              "X-CSRFToken": getCookie("csrftoken")
            },
            body: JSON.stringify(data)
          })
          .then(function (response) {
            return response.json();
          })
          .then(function(data) {
            if (data.status) {
              return location.reload();
            }
            else{
              Swal.fire({
                title: "Oops! Can't create user!",
                icon: 'error',
                text: 'Error: ' + htmlEncode(data.error),
              })
            }

          })
          .catch(function() {
            swal.insertQueueStep({
              type: 'error',
              title: 'Oops! Unable to update user!'
            })
          })
          resolve()
        })
      }
  });

  const passwordInput = document.getElementById('create_password');
  const showPasswordCheckbox = document.getElementById('show-password');


  showPasswordCheckbox.addEventListener('change', function() {
    if (showPasswordCheckbox.checked) {
      passwordInput.type = 'text';
    } else {
      passwordInput.type = 'password';
    }
  });

}

</script>
{% endblock page_level_script %}
